<template>
  <div class="message-sender">
    <el-card class="sender-card">
      <template #header>
        <div class="card-header">
          <span>发送消息</span>
        </div>
      </template>

      <el-form
        ref="messageFormRef"
        :model="messageForm"
        :rules="messageRules"
        label-width="100px"
      >
        <el-form-item label="消息类型" prop="type">
          <el-select v-model="messageForm.type" placeholder="请选择消息类型">
            <el-option label="个人消息" value="personal" />
            <el-option label="系统通知" value="system" />
            <el-option label="广播消息" value="broadcast" />
          </el-select>
        </el-form-item>

        <el-form-item
          label="接收者"
          prop="receiver_id"
          v-if="messageForm.type === 'personal'"
        >
          <el-select
            v-model="messageForm.receiver_id"
            placeholder="请选择接收者"
            filterable
            remote
            :remote-method="searchUsers"
            :loading="userLoading"
          >
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="标题" prop="title">
          <el-input v-model="messageForm.title" placeholder="请输入消息标题" />
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input
            v-model="messageForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入消息内容"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitMessage" :loading="sending">
            发送消息
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { sendMessage } from '@/api/messages'
import { getUserList } from '@/api/users'

// 表单引用
const messageFormRef = ref()

// 响应式数据
const sending = ref(false)
const userLoading = ref(false)
const userList = ref([])

// 消息表单数据
const messageForm = reactive({
  type: 'personal',
  receiver_id: null,
  title: '',
  content: ''
})

// 表单验证规则
const messageRules = {
  type: [
    { required: true, message: '请选择消息类型', trigger: 'change' }
  ],
  receiver_id: [
    { required: true, message: '请选择接收者', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入消息标题', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入消息内容', trigger: 'blur' }
  ]
}

// 搜索用户
const searchUsers = async (query) => {
  if (!query) {
    userList.value = []
    return
  }

  userLoading.value = true
  try {
    const response = await getUserList({
      page: 1,
      pageSize: 20,
      search: query
    })

    if (response.data && response.data.list) {
      userList.value = response.data.list
    }
  } catch (error) {
    console.error('搜索用户失败:', error)
    ElMessage.error('搜索用户失败')
  } finally {
    userLoading.value = false
  }
}

// 发送消息
const submitMessage = async () => {
  try {
    await messageFormRef.value.validate()

    sending.value = true

    // 准备发送数据
    const sendData = {
      title: messageForm.title,
      content: messageForm.content,
      type: messageForm.type
    }

    // 如果是个人消息，添加接收者信息
    if (messageForm.type === 'personal') {
      const receiver = userList.value.find(user => user.id === messageForm.receiver_id)
      if (receiver) {
        sendData.receiver_id = receiver.id
        sendData.receiver_name = receiver.name
      }
    }

    const response = await sendMessage(sendData)

    if (response.code === 201) {
      ElMessage.success('消息发送成功')
      resetForm()
      // 发送成功后触发一个事件，让父组件知道需要刷新消息列表
      emit('message-sent')
    } else {
      ElMessage.error(response.message || '消息发送失败')
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('消息发送失败')
  } finally {
    sending.value = false
  }
}

// 重置表单
const resetForm = () => {
  messageFormRef.value.resetFields()
  messageForm.type = 'personal'
  messageForm.receiver_id = null
  messageForm.title = ''
  messageForm.content = ''
  userList.value = []
}

// 定义事件发射器
const emit = defineEmits(['message-sent'])

// 组件挂载时获取用户列表
onMounted(async () => {
  await searchUsers('')
})
</script>

<style scoped lang="scss">
.message-sender {
  padding: 20px;

  .sender-card {
    :deep(.el-card__header) {
      background-color: #f5f7fa;
      border-bottom: 1px solid #ebeef5;
    }

    .card-header {
      font-size: 16px;
      font-weight: 500;
      color: #333;
    }
  }
}
</style>
